import json

import xlrd
from django.db import transaction
from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
from rest_framework.generics import GenericAPIView, ListAPIView
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from rest_framework.views import APIView

from purchase.models import Purchase
from purchase.serializers import PurchaseSerializer, PurchaseUpdateSerializer


# class PurchaseListView(GenericAPIView):
#     """采购列表"""
#
#     serializer_class = PurchaseSerializer
#
#     def get(self, request):
#         serializer = self.get_serializer()
#         queryset = Purchase.objects.all().order_by('create_time')
#         print(list)
#         data_dict = {}
#         data_list = []
#         # for i in list:
#         #     print(i.create_time)
#         #     print(type(i))
#         for i in queryset:
#             # print(i.id, i.order_id, i.sku_id, i.email, i.asin, i.image_url, i.color_size, i.chinese_node,
#             # i.sell_price, i.pick_price, i.road_price, i.weight, i.numbers, i.abroad_price, i.principal, i.profit, i.pick_goods_url, i.create_time)
#             data_dict = {
#                 'id': i.id,
#                 'order_id': i.order_id,
#                 'sku_id': i.sku_id,
#                 'email': i.email,
#                 'asin': i.asin,
#                 'image_url': i.image_url,
#                 'color_size': i.color_size,
#                 'chinese_node': i.chinese_node,
#                 'sell_price': i.sell_price,
#                 'pick_price': i.pick_price,
#                 'road_price': i.road_price,
#                 'weight': i.weight,
#                 'numbers': i.numbers,
#                 'abroad_price': i.abroad_price,
#                 'principal': i.principal,
#                 'profit': i.profit,
#                 'pick_goods_url': i.pick_goods_url,
#                 'create_time': i.create_time,
#             }
#
#             data_list.append(data_dict)
#         print(data_list)
#
#         return HttpResponse(data_list)
from users.models import User



class StandardPageNumberPagination(PageNumberPagination):
    page_size = 10
    page_size_query_description = 'page_size'
    max_page_size = 100


class PurchaseUploadView(APIView):
    """上传采购文件"""
    def post(self, request):
        json_data = request.POST.get('user_id')
        print(json_data, type(json_data))

        if not json_data:
            return Response({'error_msg': '缺少参数user_id'})
        user_id = int(json_data)

        # 接收文件
        try:
            f = request.FILES['purchasefile']
        except Exception as e:
            return Response({'error_msg': str(e)})
        type_excel = f.name.split('.')[1]
        if type_excel == 'xls':
            wb = xlrd.open_workbook(filename=None, file_contents=f.read())
            table = wb.sheets()[0]
            nrows = table.nrows   # 获取行数
            ncole = table.ncols
            print(nrows, ncole)

            try:
                with transaction.atomic():
                    for i in range(1, nrows):
                        row_values = table.row_values(i)
                        # print(row_values[5], type(row_values[5]))
                        user = User.objects.get(id=user_id)
                        purchase = Purchase.objects.create(staff=user, order_id=row_values[1], sku_id=row_values[2],
                                                    email=row_values[3], asin=row_values[4], image_url=row_values[5],
                                                           color_size=row_values[6], chinese_node=row_values[7],
                                                           sell_price=row_values[8], pick_price=row_values[9],
                                                           road_price=row_values[10], weight=row_values[11],
                                                            numbers=row_values[12], abroad_price=row_values[13],
                                                           principal=row_values[14], profit=row_values[15],pick_goods_url=row_values[16],)
            except Exception as e:
                return Response({"error_msg": str(e)})

        else:
            return Response({'error_msg': '文件类型不是xls'})

        return Response({'success_msg': '导入成功'})


class PurchaseListView(ListAPIView):
    """采购列表"""
    queryset = Purchase.objects.all().order_by('-create_time')
    serializer_class = PurchaseSerializer
    pagination_class = StandardPageNumberPagination


class PurchaseDeleteView(APIView):

    """采购单删除"""
    def post(self, request):
        post_data = request.body.decode()    # 取body值
        print(post_data, type(post_data))
        post_data = json.loads(post_data)    # 转化为djct
        print(post_data['id'])

        id_list = []
        for i in post_data['id']:
            print(i)
            id_list.append(int(i))
        try:
            purchase = Purchase.objects.filter(id__in=id_list)
        except Exception as e:
            return Response({"error_msg": str(e)})
        if purchase:
            purchase.delete()
        else:
            return Response({"error_msg": "采购单不存在"})
        return Response({'success_msg': 'delete success'})


class PurchaseUpdateView(GenericAPIView):
    """修改采购单"""
    queryset = Purchase.objects.all()
    serializer_class = PurchaseUpdateSerializer

    def post(self, request):
        serializer = PurchaseUpdateSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        purchase_id = request.POST.get('id')
        try:
            print("***")
            purchase = Purchase.objects.get(id=purchase_id)
            print(purchase)
        except Exception as e:
            return Response({"error_msg": str(e)})
        try:
            user = User.objects.get(id=serializer.data['staff'])
        except Exception as e:
            return Response({"error_msg": str(e)})

        purchase.staff = user
        purchase.order_id = serializer.data['order_id']
        purchase.sku_id = serializer.data['sku_id']
        purchase.email = serializer.data['email']
        purchase.asin = serializer.data['asin']
        purchase.image_url = serializer.data['image_url']
        purchase.color_size = serializer.data['color_size']
        purchase.chinese_node = serializer.data['chinese_node']
        purchase.sell_price = serializer.data['sell_price']
        purchase.pick_price = serializer.data['pick_price']
        purchase.road_price = serializer.data['road_price']
        purchase.weight = serializer.data['weight']
        purchase.numbers = serializer.data['numbers']
        purchase.abroad_price = serializer.data['abroad_price']
        purchase.principal = serializer.data['principal']
        purchase.profit = serializer.data['profit']
        purchase.pick_goods_url = serializer.data['pick_goods_url']
        purchase.save()
        return Response({"success_msg": "update success"})

